package cn.dhnep.demo.service.impl;

import cn.dhnep.demo.mapper.PermissionMapper;
import cn.dhnep.demo.mapper.RoleMapper;
import cn.dhnep.demo.mapper.RolePermissionMapper;
import cn.dhnep.demo.pojo.Role;
import cn.dhnep.demo.pojo.RolePermission;
import cn.dhnep.demo.service.RoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author dhn
 * @since 2021-09-07
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Resource
    private RolePermissionMapper rolePermissionMapper;
    @Resource
    private PermissionMapper permissionMapper;

    @Override
    public List<Role> getAllRole(String roleName) {
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(roleName)) {
            wrapper.like("role_name", roleName);
        }

        List<RolePermission> rolePermissions = rolePermissionMapper.selectList(null); //关系表数据
        List<Role> roles = baseMapper.selectList(wrapper);
        for (Role role : roles) {
            //根据角色id查询所拥有的权限id
            List<Integer> permissionIds = rolePermissions.stream().filter(per -> per.getRoleId().equals(role.getRoleId()))
                    .map(RolePermission::getPermissionId).collect(Collectors.toList());
            if (!permissionIds.isEmpty()){
                //设置权限
                role.setPermissions(permissionMapper.selectBatchIds(permissionIds));
            }
        }
        return roles;
    }
}
